package com.lei.yohojava_002;

import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.lei.library_mvp_retrofit.http.bean.RegisterBean;
import com.lei.library_mvp_retrofit.http.rsa.RSAUtils;
import com.lei.library_mvp_retrofit.mvp.view.BaseActivity;
import com.lei.yohojava_002.contract.YoHoContract;
import com.lei.yohojava_002.model.YoHoModel;
import com.lei.yohojava_002.presenter.YoHoPresenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class RegisterActivity extends BaseActivity<YoHoPresenter> implements YoHoContract.RegisterView {
    private ImageView regBack;
    private ImageView regClose;
    private ImageView regPhoneIv;
    private Spinner regSpinner;
    private EditText regPhone;
    private LinearLayout regLlPhone;
    private EditText regYzmEt;
    private Button regYzmBt;
    private LinearLayout regLlPwd;
    private EditText regPwdEt;
    private CheckBox regPwdEye;
    private EditText regClEt;
    private Button btRegister;

    private int yzmTime = 61;
    private String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJa4C5IKvNRcLWXiLFcF4F+i1S2QAusCMszlQeJV84UetEkczjUdJ4dWbnpRkeAmXCTzRHyO67XKS6GSCuKVO/sf7cyll0i6e+d0MSWB2CTxojYingZSV6ZQO8K1Z3fJyFYSHiRhDwJ4idC80zTyKagsWV29uNa38iQYr4FwbNqZAgMBAAECgYAxV1k6W1eMMg0OsKeRabQVuwoNG3tJEnQtDdSu0zKg3vdohAyh6MR7EvmiA7g86HH8CsPd/y/9WJe/8j6sBO0Ye9gt7eyQ2NiwWvlTuwNmngcSTapVvVI6NEyJFMfQt9PB1EHLNAXlz8jtJUyA7C48jReQD9p/SzAP0VxG7lwyMQJBAOjE7hAZ/6fyP3DB1fG7jr9gONZcz3TUaqx6BUn4GKZnckW08ht9Xqcqft5Hthu8BbLM9ptQ0U8QZekrJwD6ya0CQQClwstZMPu8jLhsgugVwodcG1mPEOiw9Yjnmt9+WTI07Ll2uFv//hRXBnahBBnZbucUYEbUY3kqUX9b3e9TmEodAkEAybPMbxt4VDoxCy6Mi/pxChkBZ4/pHV3sSiU6bAyWn6vIc+sGWRfca5MBePA/N+1IKtY9Y/02QwL8rH5+P/URyQJAL/hdjORGFdzLimuf6pwvPBKWKncEQCHuisghIZmClBpl2duklELddAnkztg2+tvDd/wcw14+NGb9aoKhvhl2aQJAbvcgoPU+xs0CjeexH+TS2S/jKkTRpvP2CpPK/k71m13xWdE8RtMkYY1measRmlIwOfWze7ll/PGT4dxWf31FNg==\n";
    @Override
    public int bindLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        regBack = (ImageView) findViewById(R.id.reg_back);
        regClose = (ImageView) findViewById(R.id.reg_close);
        regPhoneIv = (ImageView) findViewById(R.id.reg_phone_iv);
        regSpinner = (Spinner) findViewById(R.id.reg_spinner);
        regPhone = (EditText) findViewById(R.id.reg_phone);
        regLlPhone = (LinearLayout) findViewById(R.id.reg_ll_phone);
        regYzmEt = (EditText) findViewById(R.id.reg_yzm_et);
        regYzmBt = (Button) findViewById(R.id.reg_yzm_bt);
        regLlPwd = (LinearLayout) findViewById(R.id.reg_ll_pwd);
        regPwdEt = (EditText) findViewById(R.id.reg_pwd_et);
        regPwdEye = (CheckBox) findViewById(R.id.reg_pwd_eye);
        regClEt = (EditText) findViewById(R.id.reg_cl_et);
        btRegister = (Button) findViewById(R.id.bt_register);
    }

    @Override
    public void initData() {
        mPresenter = new YoHoPresenter(new YoHoModel(), this);
        regClEt.addTextChangedListener(new MyEditTextReg());
        regPwdEt.addTextChangedListener(new MyEditTextReg());
        regPhone.addTextChangedListener(new MyEditTextReg());
        regYzmEt.addTextChangedListener(new MyEditTextReg());

        regBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });
        regClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //点击获取验证码
        regYzmBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (regPhone.getText().length() != 0) {
                    yzmTime = 61;
//                loginYzmBt.setEnabled(false);
                    regYzmBt.setBackgroundResource(R.drawable.bt_yzm2);
                    regYzmBt.setTextColor(Color.BLACK);
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new TimerTask() {
                                @Override
                                public void run() {
                                    if (yzmTime > 0) {
                                        --yzmTime;
                                        regYzmBt.setText("重新获取 " + yzmTime);
                                        regYzmBt.setEnabled(false);
                                    } else {
                                        regYzmBt.setText("获取验证码");
                                        regYzmBt.setTextColor(Color.WHITE);
                                        regYzmBt.setBackgroundResource(R.drawable.bt_yzm);
                                    }
                                }
                            });
                        }
                    }, 0, 1000);

                    int i1 = new Random().nextInt(9);//0-9
                    char i2 = (char) (new Random().nextInt(26) + 'A');//A-Z
                    int i3 = new Random().nextInt(9);//0-9
                    char i4 = (char) (new Random().nextInt(26) + 'a');//a-z
                    int i5 = new Random().nextInt(9);//0-9
                    char i6 = (char) (new Random().nextInt(26) + 'A');//A-Z

                    regYzmEt.setText(i1 + "" + i2 + "" + i3 + "" + i4 + "" + i5 + "" + i6);
                } else {
                    Toast.makeText(RegisterActivity.this, "请先输入手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });

        regPwdEye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (regPwdEye.isChecked()) {
                    regPwdEye.setButtonDrawable(R.drawable.login_password_see_icon);
                    regPwdEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    regPwdEye.setButtonDrawable(R.drawable.login_password_unsee_icon);
                    regPwdEt.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
                }
            }
        });

        btRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = regPhone.getText().toString().trim();
                String pwd = regPwdEt.getText().toString().trim();
                //TODO RSA加密
                byte[] buff = EncryptUtils.encryptRSA(pwd.getBytes(),
                        Base64.decode(privateKey.getBytes(), Base64.DEFAULT),
                        false, "RSA/ECB/PKCS1Padding");
                //base64
                String pwdStr = Base64.encodeToString(buff, Base64.DEFAULT);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("username",name);
                    jsonObject.put("password",pwdStr);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("ljl", "pwdStr:" + jsonObject.toString());

                mPresenter.register(jsonObject.toString());
            }
        });

    }

    @Override
    public void inJect() {

    }

    @Override
    public void getReg(RegisterBean registerBean) {
        String statues = registerBean.getStatues();
        if (statues.equals("1")) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
            finish();
        }
    }

    class MyEditTextReg implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            //输入中
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            //输入后
            if (regYzmEt.getText().length() != 0 && regPhone.getText().length() != 0 && regPwdEt.getText().length() != 0 && regClEt.getText().length() != 0) {
                btRegister.setEnabled(true);
                btRegister.setBackgroundColor(Color.BLACK);
            } else {
                btRegister.setEnabled(false);
                btRegister.setBackgroundColor(Color.GRAY);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            //输入前
        }
    }
}
